//
//  AddNewsView.m
//  Pink
//
//  Created by ZhongDaYunKe on 15/12/7.
//  Copyright © 2015年 ycy. All rights reserved.
//

#import "AddNewsView.h"


@interface AddNewsView ()
{
    YYTextView *contentView;
}



@end


@implementation AddNewsView

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

- (instancetype)init
{
    self = [super init];
    if (self) {
     }
    return self;
}

- (void)hideKeyboard
{
    [self endEditing:YES];
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [self removeObserver:self forKeyPath:@"shouldWait"];
}

- (void)initializeView
{
     _shouldWait = NO;
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(hideKeyboard) name:YYTEXTVIEWHIDEKEYBOARDNOTIFICATION object:nil];
    WS(weakself);
    dispatch_async(dispatch_get_main_queue(), ^{
        weakself.backgroundColor = [UIColor whiteColor];
        YYTextView *titleField = [[YYTextView alloc] initWithFrame:CGRectMake(5, 5, self.size.width - 10, 30)];
        titleField.placeholderText = @"新闻标题";
        titleField.placeholderTextColor = [UIColor colorFromHexString:@"F3F0E9"];
        titleField.font = [UIFont systemFontOfSize:18];
        titleField.delegate = weakself;
        titleField.tag = 21;
        [weakself addSubview:titleField];
        
        
        YYTextView *urlField = [[YYTextView alloc] initWithFrame:CGRectMake(5, CGRectGetMaxY(titleField.frame) + 1, self.size.width - 10, 30)];
        urlField.placeholderText = @"原文链接(可不填)";
        urlField.font = [UIFont systemFontOfSize:18];
        urlField.placeholderTextColor = [UIColor colorFromHexString:@"F3F0E9"];
        urlField.delegate = weakself;
        urlField.tag = 22;
        [weakself addSubview:urlField];
        
        [weakself lineWithTextfield:titleField];
        [weakself lineWithTextfield:urlField];
        
        contentView = [YYTextView new];
        contentView.frame = CGRectMake(5, CGRectGetMaxY(urlField.frame) + 1, self.size.width - 10, self.size.height - (CGRectGetMaxY(urlField.frame) + 2));
        contentView.placeholderText = @"内容";
        contentView.delegate = weakself;
        contentView.placeholderTextColor = [UIColor colorFromHexString:@"F3F0E9"];
//        contentView.font = [UIFont systemFontOfSize:16];
        contentView.textColor = [UIColor blackColor];
        contentView.allowsPasteAttributedString = YES;
        [Commen setDoneButtonWith:contentView];
        
        [weakself addSubview:contentView];
        
        UIButton *chooseImage = [UIButton buttonWithType:UIButtonTypeCustom];
        chooseImage.frame = CGRectMake(10, CGRectGetMaxY(weakself.bounds)  - 35, 30, 30);
        chooseImage.backgroundColor = [UIColor black50PercentColor];
        [chooseImage addBlockForControlEvents:UIControlEventTouchUpInside block:^(id sender) {
            [weakself choosePhotos];
        }];
        [weakself addSubview:chooseImage];

    });
    
    
}




- (void)choosePhotos
{
    UIActionSheet *sheet;
    
    // 判断是否支持相机
    if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
    {
        sheet  = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:nil destructiveButtonTitle:@"取消" otherButtonTitles:@"拍照",@"从相册选择", nil];
    }
    else {
        
        sheet = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:nil destructiveButtonTitle:@"取消" otherButtonTitles:@"从相册选择", nil];
    }
    
    sheet.tag = 255;
    WS(weakself);
    dispatch_async(dispatch_get_main_queue(), ^{
        [sheet showInView:weakself];
    });
    
    
}

#pragma mark - actionsheet delegate

-(void)actionSheet:(UIActionSheet *)actionSheet didDismissWithButtonIndex:(NSInteger)buttonIndex
{
    if (actionSheet.tag == 255) {
        
        NSUInteger sourceType = 0;
        
        // 判断是否支持相机
        if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
            
            switch (buttonIndex) {
                case 0:
                    // 取消
                    return;
                case 1:
                    // 相机
                    sourceType = UIImagePickerControllerSourceTypeCamera;
                    break;
                    
                case 2:
                    // 相册
                    sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
                    break;
            }
        }
        else {
            if (buttonIndex == 0) {
                
                return;
            } else {
                sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
            }
        }
       
        WS(weakself);
        
        dispatch_async_on_main_queue(^{
            // 跳转到相机或相册页面
            UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
            
            imagePickerController.delegate = weakself;
            
            imagePickerController.allowsEditing = NO;
            
            imagePickerController.sourceType = sourceType;
            
            [[weakself responderController] presentViewController:imagePickerController animated:YES completion:^{}];
            
            
        });
        
        
    }
    
}

-(BOOL)textView:(YYTextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
    if (textView.tag == 21 || textView.tag == 22 ) {
        if ([text isEqualToString:@"\n"]) {
            [textView resignFirstResponder];
            return NO;
        }
    }
    return YES;
}


-(BOOL)textViewShouldEndEditing:(YYTextView *)textView
{
    
    switch (textView.tag) {
        case 21:
            _titleString = textView.text;
            break;
        case 22:
            _originUrl= textView.text;
            break;
            
        default:
            break;
    }
    
    return YES;
}


- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [[self responderController] dismissViewControllerAnimated:YES completion:^{}];
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    [picker dismissViewControllerAnimated:YES completion:^{}];
    
    UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
    
     _shouldWait = YES;
    AVFile *file = [AVFile fileWithName:@"image.jpg" data:UIImageJPEGRepresentation(image, 0.4)];

    UIImageView *imageview = [[UIImageView alloc] initWithFrame:CGRectMake(20, 0, contentView.size.width - 40, 200)];
    imageview.contentMode = UIViewContentModeScaleAspectFit;
    
    
    NSMutableAttributedString *text = [[NSMutableAttributedString alloc] initWithAttributedString:contentView.attributedText];
    
    NSMutableAttributedString *attachText = [NSMutableAttributedString attachmentStringWithContent:imageview contentMode:UIViewContentModeCenter attachmentSize:imageview.size alignToFont:[UIFont systemFontOfSize:16] alignment:YYTextVerticalAlignmentCenter];
    [text appendAttributedString:attachText];
    contentView.attributedText = text;
    
    [file saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
        if (succeeded) {
          NSLog(@"%@",file.url);
            _shouldWait = NO;
        [[NSNotificationCenter defaultCenter] postNotificationName:@"imageHasDoneUpload" object:nil];
            [imageview setImageWithURL:[NSURL URLWithString:file.url] options:YYWebImageOptionProgressiveBlur | YYWebImageOptionSetImageWithFadeAnimation];
        }else{
            
        }
    }progressBlock:^(NSInteger percentDone) {
        
    }];
}



-(void)uploadData
{
    NSMutableArray *images = [[NSMutableArray alloc] init];
    
    [contentView.attributedText enumerateAttributesInRange:NSMakeRange(0, contentView.attributedText.length) options:NSAttributedStringEnumerationLongestEffectiveRangeNotRequired usingBlock:^(NSDictionary<NSString *,id> * _Nonnull attrs, NSRange range, BOOL * _Nonnull stop) {
       
        YYTextAttachment *attachment = attrs[@"YYTextAttachment"];
        if (attachment) {
            NSLog(@"%@",((UIImageView *)attachment.content).imageURL);
            
            [images addObject:((UIImageView *)attachment.content).imageURL];
            
         }
        
    }];
    
    NSArray *arr = [contentView.text componentsSeparatedByString:@"\ufffc"];
    NSLog(@"%@",arr);
    NSInteger maxCount = images.count > arr.count ? images.count : arr.count;
    
    NSMutableArray *contentArr = [[NSMutableArray alloc] init];
    
    for (int i = 0; i < maxCount; i ++) {
      
        NSMutableDictionary *item = [[NSMutableDictionary alloc] init];
//        [item setObject:@"" forKey:@"videoPath"];
        if (i < images.count) {
            [item setObject:images[i] forKey:@"imagePath"];
        }
        if (i < arr.count) {
            [item setObject:arr[i] forKey:@"content"];
        }
        
        [contentArr addObject:item];
    }
    
    NSString *contentJson = [contentArr modelToJSONString];
    NSLog(@"%@",contentJson);
    
    News *newObj = [[News alloc]init];
    newObj.title = _titleString;
    newObj.originUrl = _originUrl;
    newObj.content = contentJson;
    newObj.userId = CurrentAVUser.objectId;

    ALERTMESSAGE(@"发布中...")
    AVIMClient *client = [[AVIMClient alloc] init];
    [client openWithCallback:^(BOOL succeeded, NSError *error) {
       
        if (succeeded) {
             [client createConversationWithName:_titleString clientIds:@[] callback:^(AVIMConversation *conversation, NSError *error) {
                 
                 if (conversation) {
                     
                     newObj.conversationId = conversation.conversationId;
                     [AVClient saveObjectWithClassName:@"News" model:newObj success:^(BOOL succeeded, NSError *error) {
                         if (succeeded) {
                             NSLog(@"success");
                             ALERTSUCCESS(@"发布成功")
                         }else{
                             ALERTFAILED(error.description)
                         }
                     }];
                 }else{
                     ALERTFAILED(@"发布失败")
                 }
                 
             }];
        
        
        }else{
            ALERTFAILED(@"发布失败")
        }
    }];
    
    
    
}



- (void)lineWithTextfield:(YYTextView *)textField
{
    textField.returnKeyType = UIReturnKeyDone;
    
    UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(CGRectGetMinX(textField.frame), CGRectGetMaxY(textField.frame), CGRectGetWidth(textField.frame), 0.5)];
    lineView.backgroundColor = [UIColor colorFromHexString:@"F3F0E9"];
    [self addSubview:lineView];
    
}



@end
